package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.RoleController
import com.zxy.supplier_system.server.entity.Authority
import com.zxy.supplier_system.server.entity.Role
import com.zxy.supplier_system.server.repository.EmployeeRoleRepository
import com.zxy.supplier_system.server.repository.RoleRepository
import com.zxy.supplier_system.server.utils.orElse404
import jakarta.transaction.Transactional
import org.springframework.stereotype.Service

@Service
class RoleService(
    private val roleRepository: RoleRepository,
    private val employeeRoleRepository: EmployeeRoleRepository,
    private val systemServiceService: SystemServiceService
) {

    @Transactional
    fun createRole(addRoleRequest: RoleController.AddRoleRequest):RoleController.AddRoleResponse {
        return RoleController.AddRoleResponse(this.roleRepository.save(Role().apply {
            this.name = addRoleRequest.name
            this.systemService = systemServiceService.getCurrentSystemService()
        }).id!!)
    }

    fun getRoles() : List<RoleController.RoleResponse> {
        return this.roleRepository.findAllBySystemService(systemServiceService.getCurrentSystemService()).map {
            RoleController.RoleResponse(
                it.id!!,
                it.name,
                it.authorities,
                employeeRoleRepository.countByRoleAndEmployee_SystemService_Id(it,systemServiceService.getCurrentSystemService().id)
            )
        }
    }

    @Transactional
    fun updateRoleName(name: String, updateRoleNameRequest: RoleController.UpdateRoleNameRequest) {
        val role = this.roleRepository.findByNameAndSystemService(name,systemServiceService.getCurrentSystemService()).orElse404()
        role.name = updateRoleNameRequest.name
        this.roleRepository.save(role)
    }

    @Transactional
    fun deleteRole(name: String) {
        this.roleRepository.deleteByNameAndSystemService(name,systemServiceService.getCurrentSystemService())
    }

    @Transactional
    fun updateRoleAuthorities(name: String, authorities: List<Authority>) {
        val role = this.roleRepository.findByNameAndSystemService(name,systemServiceService.getCurrentSystemService()).orElse404()
        role.authorities = authorities.toMutableList()
        this.roleRepository.save(role)
    }

    @Transactional
    fun getRoleAuthorities(name: String): MutableList<Authority> {
        val role = this.roleRepository.findByNameAndSystemService(name,systemServiceService.getCurrentSystemService()).orElse404()
        return role.authorities
    }

}